<template>
  <div>
    <el-form ref="formRef" label-width="80px" :model="form" :rules="formRules">
      <!-- 第一行 -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="form.username" size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="form.workNumber" size="small" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" size="small"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="部门" prop="departmentName">
            <el-cascader
              v-model="form.departmentName"
              :options="treeData"
              :props="casProps"
              size="small"
              style="width: 100%"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="form.timeOfEntry"
              type="daterange"
              range-separator="至"
              start-placeholder="入职日期"
              end-placeholder="转正日期"
              size="small"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="form.formOfEmployment" placeholder="" size="small">
              <el-option v-for="item in hireType" :key="item.id" :label="item.value" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 员工头像 -->
      <el-form-item label="员工照片">
        <!-- :before-upload 的触发时机是选择文件之后 -->
        <!-- 在 :before-upload 里面，可以判断文件的类型和文件的大小 -->
        <!-- action 是默认要把头像上传到的地址 -->
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" v-img-error :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <p class="tips">图片格式为<strong>JPG/PNG/GIF</strong>,且大小在<strong>2MB</strong>内</p>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" size="mini" @click="onConfirm">保存更新</el-button>
        <el-button type="primary" size="mini" @click="router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmpInfoAPI, updateEmpAPI } from '@/api/emp.js'
import { getDepartListAPI } from '@/api/depart.js'
import empConst from '@/api/constant/employees.js'
import { arr2Tree, uploadFile2COS } from '@/utils/index.js'
export default {
  name: 'Personaldetail',
  data() {
    return {
      imageUrl: '',
      form: {},
      formRules: {
        username: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        workNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确手机号', trigger: 'blur' }
        ],
        departmentName: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        timeOfEntry: [{ required: true, message: '入职时间不能为空', trigger: 'change' }],
        formOfEmployment: [{ required: true, message: '转正时间不能为空', trigger: 'change' }]
      },
      treeData: [],
      hireType: empConst.hireType,
      casProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'name',
        label: 'name'
      },
      avatarFile: null
    }
  },
  created() {
    this.initEmpInfo()
    this.initDepartList()
  },
  methods: {
    async initEmpInfo() {
      const result = await getEmpInfoAPI(this.$route.params.id)
      // console.log(result)
      this.form = result.data
      this.imageUrl = result.data.staffPhoto
    },
    async initDepartList() {
      const res = await getDepartListAPI()
      console.log(res)
      this.treeData = arr2Tree(res.data.depts, '')
    },
    beforeAvatarUpload(file) {
      // 允许当作头像上传的图片类型
      const allowTypes = ['image/jpeg', 'image/png', 'image/gif']
      const isAllowTypes = allowTypes.includes(file.type)
      // const isJPG = file.type === 'image/jpeg'
      // 判断图片是否在 2M 内
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isAllowTypes) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
        // 阻止 el-upload 自带的头像上传行为
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        // 阻止 el-upload 自带的头像上传行为
        return false
      }
      this.imageUrl = URL.createObjectURL(file)
      this.avatarFile = file
      console.log('可以上传图片了')
      // 阻止 el-upload 自带的头像上传行为
      return false
    },
    onConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.avatarFile) {
          const result = await uploadFile2COS(this.avatarFile)
          // console.log(result)
          this.form.staffPhoto = 'https://' + result.Location
        }
        const form = { ...this.form }
        // 判断 departmentName 是否为数组
        if (Array.isArray(form.departmentName)) {
          form.departmentName = [...form.departmentName].pop()
        }
        await updateEmpAPI(form)
        this.$message.success('更新成功')
        this.$router.back()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.tips {
  margin: 0;
  font-size: 12px;
}
</style>
